﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace LVYAN.Utils
{
    /// <summary>
    /// 
    /// </summary>
    public class SignService
    {

        public string MD5ToUpper(string data)
        {

            string ret = string.Empty;
            byte[] b = Encoding.UTF8.GetBytes(data);
            b = new MD5CryptoServiceProvider().ComputeHash(b);
            for (int i = 0; i < b.Length; i++)
                ret += b[i].ToString("X").PadLeft(2, '0');
            return ret;
        }
        public string MD5ToLower(string data)
        {
            string ret = string.Empty;
            byte[] b = Encoding.UTF8.GetBytes(data);
            b = new MD5CryptoServiceProvider().ComputeHash(b);
            for (int i = 0; i < b.Length; i++)
                ret += b[i].ToString("x").PadLeft(2, '0');
            return ret;
        }
        public string HMACSHA256ToBase64(string message, string secret)
        {
            byte[] keyByte = Encoding.UTF8.GetBytes(secret);
            byte[] messageBytes = Encoding.UTF8.GetBytes(message);
            using (var hmacsha256 = new HMACSHA256(keyByte))
            {
                byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
                return Convert.ToBase64String(hashmessage);
            }
        }

        public string ToBase64String(string content)
        {
            byte[] contentByte = Encoding.UTF8.GetBytes(content);
            content = Convert.ToBase64String(contentByte);
            return content;
        }
        public string FromBase64String(string content)
        {
            byte[] bytes = Convert.FromBase64String(content);
            content = Encoding.UTF8.GetString(bytes);
            return content;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="Data"></param>
        /// <returns></returns>
        public string SignMD5(string Data)
        {
            using (var md5 = MD5.Create())
            {
                var hsah = md5.ComputeHash(Encoding.UTF8.GetBytes(Data));
                return BitConverter.ToString(hsah).Replace("-", "");
            }
        }
        public string SignMD5<T>(T t)
        {
            var Data = JsonService.ToString(t);
            return SignMD5(Data);
        }
    }
}
